import { request } from '../../request/index'
Page({

  data: {

  },

  userId: wx.getStorageSync('userId'),
  curPage: 0,

  onLoad: function (options) {
    if(options.type == 0) {
      wx.setNavigationBarTitle({
        title: '关注列表'
      })
    } else {
      wx.setNavigationBarTitle({
        title: '粉丝列表'
      })
    }
    if(JSON.parse(options.users).length <= 0) {
      wx.showModal({
        title: '提示',
        content: '为什么没有欸?',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
      return
    }
    this.type = options.type
    this.setData({
      users: JSON.parse(options.users)
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getFellow(this.userId, 0, this.type)
    this.curPage = 0
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.curPage += 1
    this.getFellow(this.userId, this.curPage, this.type)
  },

  // 获取关注列表
  async getFellow(userid, curPage, type) {
    let res = null
    if(type == 0) {
      res = await request({
        url: `/follows/${userid}/${curPage}`,
        method: 'post'
      })
    } else {
      res = await request({
        url: `/fans/${userid}/${curPage}`,
        method: 'post'
      })
    }
    if(res.data.state == -2) {
      wx.showToast({
        title: '太快了哦',
        icon: 'error',
        duration: 1500,
      })
      wx.stopPullDownRefresh()
      return
    }
    const users = res.data.users.users
    if(users.length <= 0) {
      this.curPage -= 1
      wx.showToast({
        title: '没有了哦',
        icon: 'none',
        duration: 1500,
      })
      wx.stopPullDownRefresh()
      return
    }
    users.forEach(item => {
      const headpic = item.headpic.split('"')[1]
      const nickname = item.nickname.split('"')[1]
      item.headpic = headpic
      item.nickname = nickname
    })
    this.setData({
      users
    }, () => {
      wx.stopPullDownRefresh()
    })
  },

  handUser(e) {
    const { userid } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/personal/personal?userId=${userid}`
    })
  },
})